package online.hxstar.learn.chapter2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author xinghu
 * @version 1.0
 * @date 2019/11/7 4:56 下午
 */
@Slf4j
public class EchoServer {

	private final int port;

	public EchoServer(int port) {
		this.port = port;
	}

	public static void main(String[] args) throws InterruptedException {
		Scanner scanner = new Scanner(System.in);
		int num = scanner.nextInt();
		if (num != 0) {
			log.error("Usage: " + EchoServer.class.getSimpleName() + " <port>");
		} else {
			log.error("Usage: " + num + " <port>");
		}
		new EchoServer(num).start();
	}

	private void start() throws InterruptedException {
		final EchoServerHandler echoServerHandler = new EchoServerHandler();
		//创建 Event- LoopGroup
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			// 创建 Server- Bootstrap
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(group)
					//指定所使用的 NIO 传输 Channel
					.channel(NioServerSocketChannel.class)
					//使用指定的 端口设置套 接字地址
					.localAddress(new InetSocketAddress(port))
					// 添加一个 EchoServer- Handler 到子 Channel 的 ChannelPipeline
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							// EchoServerHandler 被 标注为@Shareable，所 以我们可以总是使用 同样的实例
							ch.pipeline().addLast(echoServerHandler);
						}
					});
			ChannelFuture future = serverBootstrap.bind().sync();
			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}
	}
}
